import sys
sys.path.append("..")
import traceback
from logger import log
from entites import *
import datetime
from mongoengine import *
from datetime import datetime
import random
connect('music')

class DBI:
    
    autoCommit=True
    
    def __init__(self):
        pass
    def endSession(self):
        pass        
    def getTrack(self):
        return list(Track.objects.limit(400).order_by('-likes'))
    def getUser(self,user_id):
        return User.objects.filter(user_id=user_id).first()
    def saveUser(self,created,user_id,name=None,access_token=None,profile_url=None,facebook=None ):
        u=User(created=created,user_id=user_id,name=name,access_token=access_token,profile_url=profile_url,facebook=facebook)
        log.debug("will check if user exists")
        user=self.getUser(user_id)
        if user:
            log.debug("user exists will merge")
            u.id=user.id
        else:
            log.debug("user doesn't exist will create a new one")
        u.save()
        return u
    def addRequest(self,user,track,action=None):
        r=Request(user=user,request=track,created=datetime.now(),action=action)
        r.save()
    def addTrackLog(self,user,track,action,position,show):
        log.debug("position "+str(position))
        l=TrackLog(user=user,track=track,created=datetime.now(),action=action,position=str(position),show=show)
        l.save()
    def userHistory(self,user):
        history=TrackLog.objects.filter(user=user)
        historySet=set()
        for item in history:
            historySet.add(item.track)
        return historySet
    def getTrackById(self,track):
        track=Track.objects.filter(md5=track).first()
        return track
    def getTopArtists(self):
        artists=Artist.objects.limit(10).order_by('-likes')
        names=[]
        for artist in artists:
            names.append(artist.name)
        return names
    def getTracksbyArtists(self,artists):
        return list(Track.objects(artist_name__in=artists).limit(10).skip(random.randint(0,400)).order_by('-likes'))
    def get_show(self,show):
        log.debug(show)
        show= Show.objects.filter(name=show).first()
        log.debug(show)
        tracks=show['tracks']
        name=show.name_ar
        log.debug(tracks)
        return tracks,name
          
        
        
        
        